package org.jflame.devAide;

import org.jflame.devAide.controller.Main1Controller;
import org.jflame.devAide.service.FileService;
import org.jflame.devAide.service.ThreadService;
import org.jflame.devAide.util.Loger;
import org.jflame.devAide.util.ResourceUtils;
import org.jflame.fx.util.FxUtils;

import java.io.IOException;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

/**
 * devAide main app
 */
public class App extends Application {

    @Override
    public void init() throws Exception {
        AppContext.setHostServices(getHostServices());

        FileService.initBaseDir();
        ThreadService.instance()
                .runActionLater(() ->
                {
                    try {
                        FileService.initDataFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }, false);

    }

    @Override
    public void start(Stage stage) throws IOException {
        // 未捕获异常记录日志
        Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
            Loger.error(throwable);
        });

        Parent parent = FxUtils.loadFXML(ResourceUtils.fxmlUrl("main1"), new Main1Controller());

        // JFLDecorator decorator = UIUtils.decorator(stage, parent, AppContext.appTitle(), "logo16X16.png");

        Scene scene = new Scene(parent, 1280, 800);
        scene.getStylesheets()
                .addAll(AppContext.BASE_STYLE_FILES);

        stage.setResizable(false);
        stage.setMinWidth(1280);
        stage.setMinHeight(800);
        stage.setScene(scene);
        // stage.setFullScreen(true);
        // stage.setMaximized(true);
        stage.setResizable(true);
        stage.setTitle(AppContext.appTitle());
        stage.getIcons()
                .add(new Image(ResourceUtils.imageUrl("logo32X32.png")));
        stage.show();
        stage.setOnCloseRequest(new EventHandler<WindowEvent>() {

            @Override
            public void handle(WindowEvent event) {
                Platform.exit();
                System.exit(0);
            }
        });

        AppContext.setMainStage(stage);
    }

    public static void main(String[] args) {
        launch(args);
    }

}
